﻿// ParseLib - An open source library for natural language processing.
// Copyright (C) Kais Dukes, 2012. E-mail: kais@kaisdukes.com
// http://parselib.org

using System.Collections.Generic;
using System.Linq;
using Ionic.Zip;
using ParseLib.Arabic.Corpora.CorpusReader;
using ParseLib.Corpora;
using ParseLib.Tagging;
using ParseLib.Treebanks;

namespace ParseLib.Arabic.Corpora
{
    public class QuranicArabicCorpus : DependencyTreebank
    {
        private SyntaxGraph[] _graphs;

        public QuranicArabicCorpus()
        {
            PartOfSpeechTagset = new PartOfSpeechTagset();
            DependencyTagset = new DependencyTagset();
        }

        public override TextualUnit this[int index]
        {
            get { return _graphs[index]; }
        }

        public SyntaxGraph GetGraph(Location location)
        {
            return _graphs.SingleOrDefault(
                x => x.Nodes.Cast<ArabicNode>().Any(
                    y => location.Equals(y.Location)));
        }

        public override void Load()
        {
            using (var zipFile = new ZipFile(Source))
            {
                Load(zipFile);
            }
        }

        private void Load(IEnumerable<ZipEntry> zipFile)
        {
            // Open ZIP file.
            var zipStream = zipFile.Single().OpenReader();

            // Read corpus.
            var graphs = new List<SyntaxGraph>();
            using (var quranicReader = new QuranicReader(this, zipStream))
            {
                SyntaxGraph graph;
                while ((graph = quranicReader.ReadGraph()) != null)
                {
                    graphs.Add(graph);
                }
            }

            // Load graphs.
            _graphs = graphs.ToArray();
            TextualUnitCount = _graphs.Length;
        }
    }
}